import _ from 'lodash';
import moment from 'moment';

/**
 * 计算相对路径。
 * @param from 起始路径，应当是绝对路径。
 * @param to 目标路径，应当是绝对路径。
 * @return 从`from`到达`to`的相对路径。
 */
export const relative = (from: string, to: string): string => {
    if (from.startsWith('/')) {
        from = from.substring(1);
    }
    if (to.startsWith('/')) {
        to = to.substring(1);
    }

    const path1Array = from.split('/');
    const path2Array = to.split('/');
    const cn = Math.min(path1Array.length, path2Array.length);

    // 计算公共部分。
    let ccn = 0;
    for (let i = 0; i < cn; ++i) {
        if (path1Array[i] === path2Array[i]) {
            ccn = i + 1;
        } else {
            break;
        }
    }

    return [...Array<string>(path1Array.length - ccn).fill('..'), ...path2Array.slice(ccn)].join('/') || './';
};

export const ready = (callback: () => void): void => {
    document.addEventListener('DOMContentLoaded', callback!);
};

export const formatDate = (d: Date | number): string => {
    return moment(d).format('YYYY.MM.DD');
};

export const formatLongDate = (d: Date | number): string => {
    return moment(d).format('YYYY.MM.DD HH:mm:ss');
};

export const formatFromNow = (d: Date | number): string => {
    return moment(d).fromNow();
}

export const formatToNow = (d: Date | number): string => {
    return moment(d).toNow();
}

export const formatNumber = (n: string | number, fractionDigits: number = 2, percent: boolean = false): string => {
    if (n === null || n === undefined) {
        return '';
    }

    if (fractionDigits < 0) {
        fractionDigits = 0;
    }

    if (typeof n === 'number') {
        n = n.toFixed(fractionDigits);
    } else {
        n = n.trim();
    }

    const isNegative = n.startsWith('-');

    n = n.replace(/[^0-9.]/, '');// Remove all non-digits

    const ns: string[] = n.split('.', 3);
    let n1: string = '';
    let n2: string = '';
    n1 = ns[0];
    if (ns.length >= 2) {
        n2 = ns[1];
    }

    if (n1 === '') {
        if (n2 === '') {
            return '';
        }

        n1 = '0';
    }

    if (percent) {
        // Move 2 digits from n2 to n1
        const nn: string = (n2 + '00').substring(0, 2);
        n1 = n1 + nn;
        n2 = n2.substring(2);
    }

    n1 = n1.replace(/^0+(?=\d)/, ''); // Remove leading zero
    n1 = n1.replace(/(\d)(?=(\d{3})+$)/g, '$1,'); // Add comma
    if (isNegative) {
        n1 = '-' + n1;
    }

    if (fractionDigits > n2.length) {
        n2 = n2 + _.repeat('0', fractionDigits - n2.length);
    } else if (fractionDigits < n2.length) {
        n2 = n2.substring(0, fractionDigits);
    }

    if (n2 !== '') {
        return n1 + '.' + n2;
    } else {
        return n1;
    }
};

export const formatPercent = (n: string): string => {
    const s = formatNumber(n, 2, true);
    return s !== '' ? s + '%' : '';
};

export const formatBool = (b: boolean): string => {
    return _.isBoolean(b) ? b ? '是' : '否' : '';
};

export const strEqual = (a: any, b: any): boolean => {
    const sa = a !== null && a !== undefined ? a.toString() : '';
    const sb = b !== null && b !== undefined ? b.toString() : '';

    return sa === sb;
};

export const urlSafeBtoa = (s: string): string => {
    if (!s) {
        return '';
    }

    return btoa(encodeURIComponent(s)).replace(/\+|\/|=/gi, ch => ch === '+' ? '-' : ch === '/' ? '_' : '');
};

export const urlSafeAtob = (s: string): string => {
    if (!s) {
        return '';
    }

    s = s.replace(/-|_/, ch => ch === '-' ? '+' : '/');
    const pc = s.length % 4;
    if (pc !== 0) {
        s = s + '===='.substr(0, pc);
    }

    return decodeURIComponent(atob(s));
};

export interface ITextValuePair {
    text: string,
    value?: any,
};

// const navigator: any = window.navigator as any;
// moment.locale(navigator.userLanguage || navigator.language);
moment.locale('zh-cn');

if (typeof process !== 'object' || (process as any).browser) {
    console.info('%cSys module (2.1.0) loaded', 'font-weight:bold;color: #4baf50;');
};